import { login, logout, getInfo } from '@/api/user'
import { getUserRoleList } from '@/api/role'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.jwtToken)
        setToken(data.jwtToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(async response => {
        const { data } = response

        if (!data) {
          reject('未获取到账号信息，请重新登录')
        }

        const { user_role, user_name } = data
        
        const res = await getUserRoleList({ roles: user_role })
        const midList = []
        res.data.forEach(item => {
          midList.push(...item.role_menu)
        });
        const menus = [...new Set(midList)]
        // roles must be a non-empty array
        if (!menus || menus.length <= 0) {
          reject('角色权限菜单为空')
        }
        data.menus = menus
        commit('SET_ROLES', user_role)
        commit('SET_NAME', user_name)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

